/**
 * 
 */
package com.iwords.service.persistence.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

import com.iwords.service.object.MessageEntity;
import com.iwords.service.object.UserEntity;
import com.iwords.service.object.UserSysConfigEntity;
import com.iwords.service.persistence.UserPersistence;

/**
 * @author       BOLIN.HBC 
 * @time         2011-3-10    
 * @description  User-PersistenceImpl       
 */
@Stateless
public class UserPersistenceImpl implements UserPersistence {

    @PersistenceContext(unitName = "iwords")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public void create(UserEntity entity) {
        getEntityManager().persist(entity);
    }

    public UserEntity findUser(UserEntity user) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userid", user.getUserid());
        map.put("username", user.getUsername());
        map.put("nickname", user.getNickname());
        return getEntityManager().find(UserEntity.class, map);
    }

    public void edit(UserEntity entity) {
        getEntityManager().merge(entity);
    }

    public void remove(UserEntity entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public UserEntity find(Object id) {
        return getEntityManager().find(UserEntity.class, id);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public List<UserEntity> findAll() {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(UserEntity.class));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<UserEntity> findByTeacherId(Long teacherid) {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(UserEntity.class));
        return getEntityManager().createQuery("SELECT i FROM UserEntity i WHERE i.teacherid = :teacherid").setParameter("teacherid", teacherid).getResultList();

    }

    @SuppressWarnings("unchecked")
    public List<UserEntity> findRange(int[] range) {
        CriteriaQuery<Object> cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(UserEntity.class));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return (List<UserEntity>) q.getResultList();
    }

    public int count() {
        CriteriaQuery<Object> cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<UserEntity> rt = cq.from(UserEntity.class);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

    public UserEntity find(UserEntity user) {

        Query query = getEntityManager().createQuery("SELECT s from UserEntity s where s.username=?1 and s.password=?2");
        query.setParameter(1, user.getUsername());
        query.setParameter(2, user.getPassword());
        MessageEntity message = getUserMessage(0L);

        try {
            UserEntity entity = (UserEntity) query.getSingleResult();
            if (message != null) {
                entity.setMessage(message.getMessage());
                entity.setMessageid(message.getId());
                entity.setType(message.getMessagetype());
            }
            return entity;
        } catch (NoResultException e) {
            return null;
        }
    }

    private MessageEntity getUserMessage(Long userid) {
        // userid暂时无用
        Query query = getEntityManager().createQuery("SELECT s from MessageEntity s order by s.createtime desc").setFirstResult(0).setMaxResults(1);
        try {
            return (MessageEntity) query.getSingleResult();
        } catch (Exception e) {
        }
        return null;
    }

    public boolean isContain(UserEntity user) {
        Query query = getEntityManager().createQuery("SELECT s from UserEntity s where s.username=?1 ");
        query.setParameter(1, user.getUsername());

        try {
            if (query.getSingleResult() == null) {
                return false;
            }
        } catch (NoResultException e) {
            return false;
        }
        return true;
    }

    public void updateCurrentLib(UserEntity user) {
        UserEntity u = find(user.getUserid());

        u.setCurrentlib(user.getCurrentlib());
        edit(u);

    }

    @Override
    public UserEntity findUserSysConfig(Long id) {
        // TODO Auto-generated method stub

        return null;
    }

    public UserSysConfigEntity getUserConfigByUserIdToday(UserSysConfigEntity config) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String startTime = sdf.format(new Date());
        try {
            Date startDate = sdf1.parse(startTime + " 00:00:00");
            Date endDate = sdf1.parse(startTime + " 23:59:59");
            Query query = getEntityManager().createQuery(
                    "SELECT s from UserSysConfigEntity s where s.user.userid=?1 and s.configkey=?2 and s.updatetime >?3 and s.updatetime <?4");
            query.setParameter(1, config.getUser().getUserid());
            query.setParameter(2, config.getConfigkey());
            query.setParameter(3, startDate);
            query.setParameter(4, endDate);
            try {
                return (UserSysConfigEntity) query.getSingleResult();
            } catch (NoResultException e) {
            }
        } catch (ParseException e1) {
        }
        return null;

    }

    public void insertUserConfig(UserSysConfigEntity config) {

        getEntityManager().persist(config);

    }

    public void updateUserConfig(UserSysConfigEntity config) {
        getEntityManager().merge(config);

    }
}
